$.extend($.fn.datagrid.methods, {
    fixRownumber: function (jq) {
        return jq.each(function () {
            var panel = $(this).datagrid("getPanel");
            var clone = $(".datagrid-cell-rownumber", panel).last().clone();
            clone.css({
                "position": "absolute",
                left: -1000
            }).appendTo("body");
            var width = clone.width("auto").width();
            if (width > 25) {
                // 多加5个像素,保持一点边距
                $(".datagrid-header-rownumber,.datagrid-cell-rownumber", panel)
                    .width(width + 5);
                $(this).datagrid("resize");
                // 一些清理工作
                clone.remove();
                clone = null;
            } else {
                // 还原成默认状态
                $(".datagrid-header-rownumber,.datagrid-cell-rownumber", panel)
                    .removeAttr("style");
            }
        });
    }
});


/**
 * grid分页控件事件
 *
 * @param grid
 */
function changePage(grid, params, url) {
    var pg = grid.datagrid("getPager");
    if (pg) {
        $(pg).pagination(
            {
                onBeforeRefresh: function (pageNumber, pageSize) {

                },
                pageList: [25, 50, 100],
                onChangePageSize: function (pageSize) {
                    /*
                     * var rows=grid.datagrid("getChanges");
                     * if(rows.length>0){ $.messager.alert("友情提醒",
                     * "修改数据未保存，请保存数据！", "info", function(){}); return; }
                     */
                    // getPage(grid, params, url);
                },
                onSelectPage: function (pageNumber, pageSize) {
                    var rows = grid.datagrid("getChanges");
                    if (rows.length > 0) {
                        //$.messager.alert("友情提醒", "修改数据未保存，请保存数据！", "info",
                        //		function() {
                        //		});
                        $.alert("default", "info", "修改数据未保存，请保存数据！");
                        return;
                    } else {
                        params.pageNumber = pageNumber;
                        getPage(grid, params, url);
                    }
                }
            });
    }
}

/**
 * grid分页查询
 *
 * @param grid
 * @param params
 * @param url
 */
function refresh(grid, url) {
    var params = new Object();
    // 分页工具条
    var pg = grid.datagrid("getPager");
    var options = pg.pagination("options");
    // options.pageNumber = params.pageNumber;

    // var pageSize = options.pageSize;

    // 解决第二页也从1开始排序

    var gridOptions = grid.datagrid("options");
    params = gridOptions.queryParams;
    // 1.3以前版本
    params.page = options.pageNumber;
    params.rows = options.pageSize;

    // 发送请求参数
    params.pageNo = options.pageNumber;
    params.pageSize = options.pageSize;
    ;
    $.ajax({
        type: "POST",
        url: url,
        data: params,
        dataType: "json",
        success: function callback(data) {
            var analyMsg = data;

            if (analyMsg.code != "0000") {
                //$.messager.alert("友情提醒", analyMsg.msg, "info", function() {
                //});
                $.alert("default", "info", analyMsg.msg);
                return;
            }

            // Load数据
            grid.datagrid('loadData', {
                total: 0,
                rows: []
            });

            grid.datagrid("loadData", analyMsg.returnObject);
            if (analyMsg.returnObject.total > 0) {
                grid.datagrid('selectRow', 0);
            }
            displayMsg(grid);

        },
        error: function (data, textstatus) {
            alert(data.responseText);
        }
    });
}

/**
 * grid分页查询
 *
 * @param grid
 * @param params
 * @param url
 */
function getPage(grid, params, url) {
    // 分页工具条
    var pg = grid.datagrid("getPager");
    var options = pg.pagination("options");
    options.pageNumber = params.pageNumber;

    var pageSize = options.pageSize;

    // 解决第二页也从1开始排序

    var gridOptions = grid.datagrid("options");
    // 1.3以前版本
    params.page = params.pageNumber;
    params.rows = pageSize;
    gridOptions.queryParams = params;
    // 1.3版本
    gridOptions.pageNumber = params.pageNumber;
    gridOptions.pageSize = pageSize;

    // 发送请求参数
    params.pageNo = params.pageNumber;
    params.pageSize = pageSize;
    $.ajax({
        type: "POST",
        url: url,
        data: params,
        dataType: "json",
        success: function callback(data) {
            var analyMsg = data;
            //
            // if (analyMsg.code != "0000") {
            // 	//$.messager.alert("友情提醒", analyMsg.msg, "info", function() {
            // 	//});
            //    $.messager.alert("default", analyMsg.msg,"info");
            // 	return;
            // }
            // Load数据
            //
            if (analyMsg.code = "0000") {
                if (analyMsg.returnObject.total > 0) {
                    grid.datagrid("loadData", analyMsg.returnObject);
                } else {
                    grid.datagrid('loadData', {
                        total: 0,
                        rows: []
                    });
                }
            }

            displayMsg(grid);

        },
        error: function (data, textstatus) {
            $.messager.alert("default", data.responseText, "error");
        }
    });
}

/**
 * grid不分页查询
 *
 * @param grid
 * @param params
 * @param url
 */
function getData(grid, params, url) {

    $.ajax({
        type: "POST",
        url: url,
        data: params,
        dataType: "json",
        async: asyncType,
        success: function callback(data) {
            var analyMsg = data;
            // if (analyMsg.code != "0000") {
            // 	//$.messager.alert("友情提醒", analyMsg.msg, "info", function() {
            // 	//});
            // 	$.alert("default", "error", analyMsg.msg);
            // 	return;
            // }
            if (analyMsg.code == "0000") {
                grid.datagrid("loadData", analyMsg.returnObject.rows);
            }

        },
        error: function (data, textstatus) {
            //alert(data.responseText);
            // $.alert("default", "error", data.responseText);
            $.messager.alert("default", data.responseText, "error");
        }
    });
}

/**
 * grid分页条信息显示
 *
 * @param grid
 */
function displayMsg(grid) {
    var rows = grid.datagrid("getRows");
    // if (!(rows == null)) {
    if (rows.length > 0) {
        grid.datagrid('getPager').pagination({
            displayMsg: '当前显示从{from}到{to}共{total}条记录。'
        });
    } else {
        grid.datagrid('getPager').pagination({
            displayMsg: '没有记录'
        });
    }
    // }
}

/**
 * 初始化 DataGrid控件信息带checkbox多选
 *
 * @param grid
 */
function initPageGridWithCheck(grid, params, url, columns, toolbar,
                               singleSelect) {
    var f = false;
    if (singleSelect) {
        f = true;
    }
    // 初始化 DataGrid控件信息
    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: true,
        loadMsg: "",
        rownumbers: true,
        queryParams: {},
        singleSelect: f,
        nowrap: true,
        striped: true,
        idField: "id",
        remoteSort: false,
        pagination: true,
        frozenColumns: [[{
            field: 'check',
            checkbox: true
        }]],
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');
            if (data.rows.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });
    params.pageNumber = 1;
    displayMsg(grid);
    changePage(grid, params, url);

}

/**
 * 初始化 DataGrid控件信息带checkbox多选 (默认选中)
 *
 * @param grid
 */
function initPageGridWithCheckBox(grid, params, url, columns, toolbar,
                                  fieldId, singleSelect) {
    var f = false;
    if (singleSelect) {
        f = true;
    }
    // 初始化 DataGrid控件信息
    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: true,
        loadMsg: "",
        rownumbers: true,
        queryParams: {},
        singleSelect: f,
        nowrap: true,
        striped: true,
        idField: fieldId,
        remoteSort: false,
        pagination: true,
        frozenColumns: [[{
            field: 'check',
            checkbox: true
        }]],
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');

            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });
    params.pageNumber = 1;
    displayMsg(grid);
    changePage(grid, params, url);

}


/**
 * 初始化 DataGrid控件信息带checkbox多选不分页 (默认选中)
 *
 * @param grid
 */
function initGridWithCheckBox(grid, params, url, columns, toolbar,
                              fieldId, singleSelect) {
    var f = false;
    if (singleSelect) {
        f = true;
    }
    // 初始化 DataGrid控件信息
    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: true,
        loadMsg: "",
        queryParams: {},
        singleSelect: f,
        nowrap: true,
        striped: true,
        idField: fieldId,
        remoteSort: false,
        frozenColumns: [[{
            field: 'check',
            checkbox: true
        }]],
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');

            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });
    getData(grid, params, url);
}

/**
 * 初始化带分页 DataGrid控件信息
 *
 * @param grid
 */
function initPageGrid(grid, params, url, columns, toolbar, footer) {
    var ft = false;
    if (typeof (footer) != "undefind") {
        ft = footer;
    }
    // 初始化 DataGrid控件信息
    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: true,
        loadMsg: "",
        rownumbers: true,
        queryParams: params,
        singleSelect: true,
        nowrap: true,
        striped: true,
        idField: "id",
        remoteSort: false,
        pagination: true,
        showFooter: ft,
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');
            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });
    params.pageNumber = 1;
    displayMsg(grid);
    changePage(grid, params, url);

}

/**
 * 初始化带分页 DataGrid控件信息
 *
 * @param grid
 */
function initPageGridAndCheck(grid, params, url, columns, toolbar, footer) {
    var ft = false;
    if (typeof (footer) != "undefind") {
        ft = footer;
    }
    // 初始化 DataGrid控件信息
    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: true,
        loadMsg: "",
        rownumbers: true,
        queryParams: params,
        singleSelect: false,
        selectOnCheck: true,
        checkOnSelect: true,
        nowrap: true,
        striped: true,
        idField: "id",
        remoteSort: false,
        pagination: true,
        showFooter: ft,
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');
            if (data.total > 0) {
                grid.datagrid("fixRownumber");
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });
    params.pageNumber = 1;
    displayMsg(grid);
    changePage(grid, params, url);
}


/**
 * 初始化 DataGrid控件信息无分页
 *
 * @param grid
 */
function initGrid(grid, columns, toolbar) {

    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        //fit : true,
        loadMsg: "",
        rownumbers: true,
        queryParams: {},
        singleSelect: true,
        nowrap: true,
        striped: true,
        //idField : "id",
        remoteSort: false,
        // pagination : true,
        showFooter: true,
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');

            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });

}

/**
 * 无分页
 */
function initDataGridWithoutPager(grid, columns, toolbar) {

    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        //fit : true,
        loadMsg: "",
        rownumbers: true,
        queryParams: {},
        singleSelect: true,
        nowrap: true,
        striped: true,
        //idField : "id",
        remoteSort: false,
        // pagination : true,
        showFooter: true,
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');

            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });

}

/**
 * 初始化 DataGrid控件信息无分页
 *
 * @param grid
 */
function initGridWithCheck(grid, columns, toolbar) {

    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: true,
        loadMsg: "",
        rownumbers: true,
        queryParams: {},
        singleSelect: false,
        nowrap: true,
        striped: true,
        idField: "id",
        remoteSort: false,
        // pagination : true,

        frozenColumns: [[{
            field: 'check',
            checkbox: true
        }]],
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');

            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });

}

/**
 * 初始化 DataGrid控件信息无分页(单选)
 *
 * @param grid
 */
function initGridWithCheckSingleSelect(grid, columns, toolbar) {

    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: false,
        loadMsg: "",
        rownumbers: false,
        queryParams: {},
        singleSelect: true,
        nowrap: true,
        striped: true,
        idField: "id",
        remoteSort: false,
        // pagination : true,

        frozenColumns: [[{
            field: 'check',
            checkbox: true
        }]],
        columns: [columns],
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');

            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });

}


/**
 * 初始化 DataGrid控件信息无分页考虑多行表头
 *
 * @param grid
 */
function initGridWithCheckLedger(grid, columns, toolbar) {

    grid.datagrid({
        url: "",
        title: "",
        toolbar: toolbar,
        fit: true,
        loadMsg: "",
        rownumbers: true,
        queryParams: {},
        singleSelect: false,
        nowrap: true,
        striped: true,
        idField: "id",
        remoteSort: false,
        // pagination : true,

        frozenColumns: [[{
            field: 'check',
            checkbox: true
        }]],
        columns: columns,
        onLoadSuccess: function (data) {
            grid.datagrid('clearSelections');

            if (data.total > 0) {
                grid.datagrid("fixRownumber");
                grid.datagrid('selectRow', 0);
            }
        },
        onLoadError: function () {
            $("#loading").hide();
        }
    });

}


